package com.example.demo.RabittMQ;

import com.example.demo.bean.GoodsSeckill;
import com.example.demo.bean.Order;
import com.example.demo.bean.User;
import com.example.demo.dao.GoodsDao;
import com.example.demo.dao.OrderDao;
import com.example.demo.exception.CodeMsg;
import com.example.demo.exception.GlobalException;
import com.example.demo.service.GoodsService;
import com.example.demo.util.JsonAndBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import sun.java2d.pipe.RenderQueue;

@Service
public class RabittMQReceiver {
    @Autowired
    private JsonAndBean jsonAndBean;

    @Autowired
    private GoodsDao goodsDao;

    @Autowired
    GoodsService goodsService;

    @Autowired
    private OrderDao orderDao;

    private static Logger log = LoggerFactory.getLogger(RabittMQReceiver.class);


    @RabbitListener(queues =RabittMQQueue.SECKILL_QUEUE)
    public void receiverMsg(String msg){
        SeckillMessage seckillMessage = jsonAndBean.JsonToBean(msg, SeckillMessage.class);
        //获得user
        User user = seckillMessage.getUser();
        if (user==null){
            throw new GlobalException(CodeMsg.SERVER_ERROR);
        }
        //获得秒杀商品的Id
        Long goodsId = seckillMessage.getGoodsId();

        //进行数据库操作
        //查询数据库中的的秒杀商品库存
        GoodsSeckill goodsSeckillAllInfro = goodsDao.findGoodsSeckillAllInfro(goodsId);


        //查出秒杀商品的库存
        Integer stockCount = goodsSeckillAllInfro.getStockCount();
        if (stockCount<=0){
            //商品被秒杀完了
            throw new GlobalException(CodeMsg.SECKILL_OVER);
        }


        ////避免重复秒杀,查看订单表中看是否以及存入
        //Order order=new Order();
        //order.setGoodsId(goodsId);
        //order.setUserId(user.getId());
        //Order orderFind = orderDao.findOrder(order);
        //if (orderFind!=null){
        //    throw new GlobalException(CodeMsg.REPEATE_SECKILL);//勿重复秒杀
        //}

        //就要开始数据库事务操作了(减掉商品库存和商品秒杀库存，还有   存入订单包括商品订单和商平秒杀订单)三者要同时操作完成，所以是事务操作.
        Integer integer = goodsService.goodsSeckill(user, goodsSeckillAllInfro);

}

    @RabbitListener(queues = RabittMQQueue.TOPIC_QUEUE1)
    public void receiveTopic1(String message) {
        log.info(" topic  queue1 message:" + message);
    }

    @RabbitListener(queues = RabittMQQueue.TOPIC_QUEUE2)
    public void receiveTopic2(String message) {
        log.info(" topic  queue2 message:" + message);
    }

}
